package fun.ticsmyc.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import fun.ticsmyc.upload.controller.UploadController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author Ticsmyc
 * @date 2020-04-29 19:09
 */
@Service
public class UploadService {

    private static final Logger LOGGER= LoggerFactory.getLogger(UploadController.class);

    //可以接受的图片类型
    private static final List<String> CONTENT_TYPES = Arrays.asList("image/gif","image/jpeg","image/png");

    //FastDFS客户端
    @Autowired
    private FastFileStorageClient storageClient;

    public String uploadImage(MultipartFile file) {
        //校验文件
        String originalFileName = file.getOriginalFilename();
        //1 校验文件类型
        String contentType = file.getContentType();
        if(!CONTENT_TYPES.contains(contentType)){
            LOGGER.info("文件上传失败：{}，文件类型不合法",originalFileName);
            return null;
        }

        //2 校验文件内容
        BufferedImage bufferedImage = null;

        try {
            bufferedImage = ImageIO.read(file.getInputStream());
            if(bufferedImage == null){
                //类型不是图片 读取失败
                LOGGER.info("文件上传失败:{}，文件类型不合法",originalFileName);
                return null;
            }
            //3 保存图片到服务器

            //获取后缀
            String ext = StringUtils.substringAfterLast(file.getOriginalFilename(),".");
            //存储
            StorePath storePath  = this.storageClient.uploadFile(file.getInputStream(),file.getSize(),ext,null);

            //返回url路径
            return "http://xxxxxxxxxxxxxxxxxxxx"+storePath.getFullPath();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
